<?php

namespace App\Extensions\Grid\Displayers;

use Encore\Admin\Grid\Displayers\AbstractDisplayer;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Arr;

class DisplayLabel extends AbstractDisplayer
{
    public function display($callback = '', $style = 'success')
    {
        if ($callback instanceof \Closure) {
            $callback = $callback->bindTo($this->row);
            $value = call_user_func_array($callback, [$this->row]);
        } else {
            $value = $callback ?: $this->value;
        }
        if ($value instanceof Arrayable) {
            $value = $value->toArray();
        }
        return collect((array)$value)->map(function ($item) use ($style) {
            if (is_array($style)) {
                if (is_int($item)) {
                    $style = Arr::get($style, $item, 'success');
                } elseif (is_string($this->getColumn()->getOriginal()) || is_int($this->getColumn()->getOriginal())) {
                    $style = Arr::get($style, $this->getColumn()->getOriginal(), 'success');
                } else {
                    $style = Arr::get($style, $item, 'success');
                }
            }
            if (is_array($style)) {
                $item = data_get($style, 0, $item);
                $style = data_get($style, 1, 'success');
            }
            return "<span class='label label-{$style}'>$item</span>";
        })->implode('&nbsp;');
    }

}
